package com.zhuss.controller;

/**
 * @author ZhouPan
 * @version V1.0
 * @ClassName: GeiTuiUtils
 * @Description: TODO(这个类的作用是 :)
 * @date 2018/9/10 18:54
 * @Copyright: 2018 www.zsplat.com Inc. All rights reserved.
 */

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.gexin.rp.sdk.base.IAliasResult;
import com.gexin.rp.sdk.base.IBatch;
import com.gexin.rp.sdk.base.IIGtPush;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.base.uitls.AppConditions;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.LinkTemplate;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.gexin.rp.sdk.template.style.Style0;
import com.zhuss.util.TimeMill;

public class GetuiUtils {

	private static String appId = "fg7kk3Bxpf8QIcBNcCh6k7";
    private static String appKey = "6KtsBcTupD8OJjrLonGlV4";
    private static String masterSecret = "Jzyk2XFEmnAJ0LgGgdSG68";
    public static String host = "https://api.getui.com/apiex.htm";
    public static IGtPush push;
    

    static {
        push = new IGtPush(host, appKey, masterSecret);
    }

    /**
     * 绑定用户cid 别名
     *
     * @param Alias
     * @param CID
     * @return
     */
    @SuppressWarnings("deprecation")
	public static boolean bindAlias(String alias, String CID) {
        IAliasResult bindSCid = push.bindAlias(appId, alias, CID);
        if (bindSCid.getResult()) {
            return true;
        }
        return false;
    }

    /**
     * 对单个用户推送消息
     *
     * @param alias
     * @param msg
     * @return
     */
    public static boolean pushMessageToSingle(String title, String cid, String text, String transMsg) {
        IGtPush push = new IGtPush(host, appKey, masterSecret);
        NotificationTemplate template = notificationTemplate(title, text, transMsg);
        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(TimeMill.一天);
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        //target.setAlias(Alias);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null && ret.getResponse() != null && ret.getResponse().containsKey("result")) {
            System.out.println(ret.getResponse().toString());
            if (ret.getResponse().get("result").toString().equals("ok") && ret.getResponse().containsKey("status")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 指定应用的所有用户群发推送消息
     *
     * @param msg
     */
    public static boolean pushtoAPP(String text, String title, String transMsg) {
        IGtPush push = new IGtPush(host, appKey, masterSecret);

        NotificationTemplate template = notificationTemplate(title, text, transMsg);
        AppMessage message = new AppMessage();
        message.setData(template);

//        message.setOffline(true);
        message.setOffline(false);
        //离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(TimeMill.一天);
        //推送给App的目标用户需要满足的条件
        AppConditions cdt = new AppConditions();
        List<String> appIdList = new ArrayList<String>();
        appIdList.add(appId);
        message.setAppIdList(appIdList);
        //手机类型
        List<String> phoneTypeList = new ArrayList<String>();
        //省份
        List<String> provinceList = new ArrayList<String>();
        //自定义tag
        List<String> tagList = new ArrayList<String>();

        cdt.addCondition(AppConditions.PHONE_TYPE, phoneTypeList);
        cdt.addCondition(AppConditions.REGION, provinceList);
        cdt.addCondition(AppConditions.TAG, tagList);
        message.setConditions(cdt);

        IPushResult ret = push.pushMessageToApp(message, "msg_toApp");

        if (ret != null && ret.getResponse() != null && ret.getResponse().containsKey("result")) {
            System.out.println(ret.getResponse().toString());
            if (ret.getResponse().get("result").toString().equals("ok")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 对单个用户推送透传消息
     *
     * @param alias
     * @param title
     * @param content
     * @return
     */
    @SuppressWarnings("deprecation")
	public static boolean pushTransMessageToSingle(String title, String cid, String msg, Integer totalNum) {
        TransmissionTemplate template = transTemplateIOS(title, cid, msg, totalNum);
        SingleMessage message = new SingleMessage();
//        message.setOffline(true);
        message.setOffline(true);
        
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(TimeMill.一天);
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        IPushResult ret = null;
        try {
             // ret = push.pushMessageToSingle(message, target);
            ret = push.pushAPNMessageToSingle(appId, cid, message);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null && ret.getResponse() != null && ret.getResponse().containsKey("result")) {
            System.out.println(ret.getResponse().toString());
            if (ret.getResponse().get("result").toString().equals("ok") && ret.getResponse().containsKey("status")) {
                return true;
            }
        }
        return false;
    }
    

    public static void pushMessageToIBatch(List<String> alias, String msg) {
        IBatch batch = push.getBatch();
        IPushResult ret = null;
        try {
            for (int i = 0; i < alias.size(); i++) {
                // 构建客户a的透传消息a
                constructClientTransMsg(alias.get(i), msg, batch);
            }
            // 构建客户B的点击通知打开网页消息b
            // constructClientLinkMsg(CID_B,"msgB",batch);
            ret = batch.submit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(ret.getResponse().toString());
    }

    private static NotificationTemplate notificationTemplate(String title, String text, String obj) {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        //template.setTransmissionType(1);
        template.setTransmissionType(2);
        template.setTransmissionContent(obj);
        // 设置定时展示时间
        // template.setDuration("2015-01-16 11:40:00", "2015-01-16 12:24:00");
        Style0 style = new Style0();
        // 设置通知栏标题与内容
        style.setTitle(title);
        style.setText(text);
        // 配置通知栏图标
        style.setLogo("XXX");
        style.setBadgeAddNum(1);
        // 配置通知栏网络图标
        //style.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        template.setStyle(style);

        return template;
    }
    
    
    private static TransmissionTemplate transTemplateIOS(String title, String cid, String msg, Integer totalNum) {
        TransmissionTemplate template = new TransmissionTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionContent(msg);
//        template.setTransmissionType(0); // 这个Type为int型，填写1则自动启动app
        template.setTransmissionType(1); // 这个Type为int型，填写1则自动启动app
        
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(1);
        //如果客户端是ios的话，需要需要设置setAPNInfo参数
        APNPayload payload = new APNPayload();
        //在已有数字基础上加1显示，设置为-1时，在已有数字上减1显示，设置为数字时，显示指定数字
        payload.setAutoBadge(totalNum + "");
        payload.setContentAvailable(0);
        payload.setSound("default");
        payload.setCategory("$由客户端定义");
        //推送消息模板 ios
        payload.setAlertMsg(getDictionaryAlertMsg(title ,msg));

        template.setAPNInfo(payload);

        return template;
    }
    
    private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(String title, String message) {
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        alertMsg.setBody(message);
        alertMsg.setActionLocKey("ActionLockey");
        // alertMsg.setLocKey("LocKey");
        alertMsg.addLocArg("loc-args");
        alertMsg.setLaunchImage("launch-image");
        // iOS8.2以上版本支持
        alertMsg.setTitle(title);
        alertMsg.setTitleLocKey(title);
        alertMsg.addTitleLocArg("TitleLocArg");
        return alertMsg;
    }

    @SuppressWarnings("unused")
	private static TransmissionTemplate transTemplate(String cid, String msg) {
        TransmissionTemplate template = new TransmissionTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionContent(msg);
//        template.setTransmissionType(0); // 这个Type为int型，填写1则自动启动app
        template.setTransmissionType(1); // 这个Type为int型，填写1则自动启动app

        return template;
    }

    //点击通知打开应用模板
    public static void constructClientTransMsg(String cid, String msg, IBatch batch) throws Exception {

        SingleMessage message = new SingleMessage();
        NotificationTemplate template = new NotificationTemplate();
//        TransmissionTemplate template = new TransmissionTemplate();//自定义模板
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionContent(msg);//消息内容
        // template.setTransmissionType(1); // 这个Type为int型，填写1则自动启动app
        template.setTransmissionType(2); // 这个Type为int型，填写1则自动启动app
        Style0 style = new Style0();        // 设置通知栏标题与内容
        style.setTitle("合同管理");
        style.setText(msg);        // 配置通知栏图标
        style.setLogo("");        // 配置通知栏网络图标
        style.setLogoUrl("");//网络图标地址
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        template.setStyle(style);

        message.setData(template);
//        message.setOffline(true);
        message.setOffline(false);
        message.setOfflineExpireTime(2 * TimeMill.一小时);

        // 设置推送目标，填入appid和clientId
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        batch.add(message, target);
    }

    //点击通知打开网页消息
    @SuppressWarnings("deprecation")
	public static void constructClientLinkMsg(String cid, String msg, IBatch batch) throws Exception {

        SingleMessage message = new SingleMessage();
        LinkTemplate template = new LinkTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTitle("title");
        template.setText(msg);
        template.setLogo("push.png");
        template.setLogoUrl("logoUrl");
        template.setUrl("http://www.baidu.com");

        message.setData(template);
//        message.setOffline(true);
        message.setOffline(false);
        message.setOfflineExpireTime(TimeMill.一分钟);

        // 设置推送目标，填入appid和clientId
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        batch.add(message, target);
    }

    public static void main(String[] args) throws IOException {

        IIGtPush push = new IGtPush(host, appKey, masterSecret);
        IBatch batch = push.getBatch();

        try {
            //构建客户a的透传消息a
            //GetuiUtils.constructClientTransMsg(CID_A, "msgA", batch);
            //构建客户B的点击通知打开网页消息b
//            constructClientLinkMsg(CID_B, "msgB", batch);
        } catch (Exception e) {
            e.printStackTrace();
        }
        batch.submit();
    }
}